package com.example.shareapp.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.shareapp.R;
import com.example.shareapp.api.UriApi;
import com.example.shareapp.bean.AllDataEntry;
import com.example.shareapp.listeners.OnclickListeners;
import com.example.shareapp.utils.DensityUtils;
import com.example.shareapp.utils.DialogUtils;
import com.example.shareapp.utils.JsonObjectUtils;
import com.example.shareapp.utils.PlatformUtil;
import com.example.shareapp.utils.ShareUtils;
import com.example.shareapp.view.LocalImageLoader;
import com.jwkj.libzxing.QRCodeManager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import cn.sharesdk.framework.PlatformActionListener;
import me.nereo.multi_image_selector.utils.FileUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.platform.Platform;


public class MainActivity extends Activity implements View.OnClickListener {
    private Context mContext;

    private Button btnJRRJ;
    private ImageView iv_banner;
    private Banner mBanner;//初始化Bnner控件使用
    private TextView tv_zb;
    private Button btn_more_software;
    private Button btn_sure;
    private Button btn_add_friends;
    private EditText et_pwd;
    private TextView tvZBName;
    private LinearLayout ll_qq_qun;
    private LinearLayout ll_luolizibo;
    private AllDataEntry mAllDataEntry;
    private int mWidth;
    private ImageView imageView;
    public static int INDEX = 0;
    private Bitmap QRcodeBitmap;
    private boolean isShare = false;
    private long time;
    private boolean isSanFang = true; //true表示第三方分享   false 表示系统分享


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mWidth = metric.widthPixels;     // 屏幕宽度（像素）
        isShare = false;
        initView();
        initnQRcodeBitmap();
        initClick();
        initBanner();
        getAsyn();
    }



    //系统
    private synchronized Bitmap initnQRcodeBitmap() {
        Bitmap bitmap = null;
        try {
            Bitmap bitmap1 = QRCodeManager.getInstance().createQRCode(UriApi.URI_QR_CODE, 400, 400);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.qz_bg);
            bitmap = mergeWithCrop(bmp, bitmap1, 0.651, 0.585);
            QRcodeBitmap = bitmap;
            if (isSanFang) {
//                iv_banner.setImageBitmap(QRcodeBitmap);
                saveBitmap(bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;

    }

    /**
     * 合成图片
     *
     * @param big      底图
     * @param small    小图
     * @param xInRatio 小图在底图中的横坐标（相对于底图宽的比例）
     * @param yInRatio 小图在底图中的纵坐标（相对于底图高的比例）
     * @return
     */
    public Bitmap mergeWithCrop(Bitmap big, Bitmap small, double xInRatio, double yInRatio) {
        Bitmap newBmp = null;
        try {

            int bigW = big.getWidth();
            int bigH = big.getHeight();
//        int dp1 = DensityUtils.px2dip(mContext,559);
//        int dp2 = DensityUtils.px2dip(mContext,230);

//            int px1 = DensityUtils.dip2px(mContext, 203);
//            int px2 = DensityUtils.dip2px(mContext, 84);

//        Log.w("hanjiming","bigW:"+bigW+" bigH:"+bigH+" dp1:"+dp1+ " dp2:"+dp2+" px1:"+px1+ " px2:"+px2);
            //scale 计算背景图被缩放的比例   1920 为本人原图实际宽度 dp1:203 dp2:84
            float scale = (float) (bigW / DensityUtils.dip2px(mContext, 203));
//        float scale = (float) (bigW / 559);
            //newsmallw 计算镶嵌图的尺寸   270为镶嵌位置实际宽高（正方形）
            int newsmallw = (int) (DensityUtils.dip2px(mContext, 84) * scale);

            newBmp = Bitmap.createBitmap(bigW, bigH, Bitmap.Config.RGB_565);
            Canvas cv = new Canvas(newBmp);


            //在0，0坐标开始画入bg
            cv.drawBitmap(big, 0, 0, null);
            //        开始画入fg，可以从任意位置画入，具体位置自己计算
            int smallX = (int) (bigW * xInRatio);
            int smallY = (int) (bigH * yInRatio);
            //设置镶嵌图片的位置
            Rect sRect = new Rect(smallX, smallY, smallX + newsmallw, smallY + newsmallw);
            //将小图镶嵌到背景图指定位置
            cv.drawBitmap(small, null, sRect, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newBmp;
    }

    private static String path;

    private synchronized void saveBitmap(Bitmap bitmap) {
        File file = new File(Environment.getExternalStorageDirectory() + "/qr.png");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            path = file.getPath();
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isSanFang) {
            checkRandom();
        }
    }

    private void checkRandom() { //定义1-7成功 8、9、10  分享失败
        if (!isShare) {
            return;
        } else {
            isShare = false;
        }
        if (System.currentTimeMillis() - time >= 1500) {
            switch (getRandom()) {
                case 8:
                case 9:
                    Toast.makeText(mContext, "分享失败，必须分享到100人群以上才可以哦", Toast.LENGTH_LONG).show();
                    refreshDialog(2);
                    break;
                case 10:
                    Toast.makeText(mContext, "分享失败，不能分享到同一个群哦", Toast.LENGTH_LONG).show();
                    refreshDialog(2);
                    break;
                default:
                    Toast.makeText(mContext, "分享成功，谢谢支持", Toast.LENGTH_LONG).show();
                    refreshDialog(1);
                    break;
            }
        } else {
            Toast.makeText(mContext, "分享失败，必须分享到100人群以上才可以哦", Toast.LENGTH_LONG).show();
            refreshDialog(2);
        }
    }

    private int getRandom() {
        java.util.Random random = new java.util.Random();// 定义随机类
        int result = random.nextInt(10);// 返回[0,10)集合中的整数，注意不包括10
        return result + 1; // +1后，[0,10)集合变为[1,11)集合，满足要求
    }

    private void initView() {
        btnJRRJ = findViewById(R.id.btn_jrrj);
        iv_banner = findViewById(R.id.iv_banner);
        tv_zb = findViewById(R.id.tv_zb);
        btn_more_software = findViewById(R.id.btn_more_software);
        btn_sure = findViewById(R.id.btn_sure);
        btn_add_friends = findViewById(R.id.btn_add_friends);
        et_pwd = findViewById(R.id.et_pwd);
        imageView = findViewById(R.id.touxian_id);
        tvZBName = findViewById(R.id.tv_zb);
        ll_qq_qun = findViewById(R.id.ll_qq_qun);
        ll_luolizibo = findViewById(R.id.ll_luolizibo);
    }

    private void initClick() {
        btnJRRJ.setOnClickListener(this);
//        iv_banner.setOnClickListener(this);
        tv_zb.setOnClickListener(this);
        btn_more_software.setOnClickListener(this);
        btn_sure.setOnClickListener(this);
        btn_add_friends.setOnClickListener(this);
        ll_qq_qun.setOnClickListener(this);
        ll_luolizibo.setOnClickListener(this);
    }


    private LocalImageLoader mImageLoader;//加载图片的工具类
    private ArrayList<String> imagePath;//存放图片的网络地址
    private ArrayList<String> imageTitle;//存放图片的title

    private void initBanner() {
        imagePath = new ArrayList<>();
        imageTitle = new ArrayList<>();
        mImageLoader = new LocalImageLoader();

    }

    private void refreshBanner() {
        mBanner = findViewById(R.id.banner_container1);
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //加载器
        mBanner.setImageLoader(mImageLoader);
        //动画效果
        mBanner.setBannerAnimation(Transformer.ZoomOutSlide);
        //图片标题
        mBanner.setBannerTitles(imageTitle);
        //间隔时间
        mBanner.setDelayTime(4500);
        //是否为自动轮播
        mBanner.isAutoPlay(false);
        //图片小点显示所在位置
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        //图片加载地址
        mBanner.setImages(imagePath);
        //启动轮播图。
        mBanner.start();
        mBanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {

                    if (mAllDataEntry != null && mAllDataEntry.aBanner != null) {
                        toWZ(mAllDataEntry.aBanner.url);
                        Log.w("hanjiming", "OnBannerClick:" + mAllDataEntry.aBanner.url);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void moreSoftware() {
        Intent intent = new Intent(this, MoreActivity.class);
        intent.putExtra("data", mAllDataEntry);
        startActivity(intent);
    }


    private void toWZ(String uriString) {
        try {
            if (TextUtils.isEmpty(uriString)) {
                Log.w("hjm", "uri is null");
                return;
            }
            //实现跳转网页的主要代码
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(uriString);
            intent.setData(content_url);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("hanjiming", e.getCause());
            Toast.makeText(mContext, "链接异常，请联系管理员", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 系统分享图片给QQ好友
     *
     * @param bitmap
     */
    public void shareImageToQQ(Bitmap bitmap) {
        if (PlatformUtil.isInstallApp(mContext, PlatformUtil.PACKAGE_MOBILE_QQ)) {
            try {
                isShare = true;
                time = System.currentTimeMillis();
                Uri uriToImage = Uri.parse(MediaStore.Images.Media.insertImage(
                        mContext.getContentResolver(), bitmap, null, null));
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
                shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                shareIntent.setType("image/*");
                // 遍历所有支持发送图片的应用。找到需要的应用
                ComponentName componentName = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
                shareIntent.setComponent(componentName);
                // mContext.startActivity(shareIntent);
                mContext.startActivity(Intent.createChooser(shareIntent, "Share"));
            } catch (Exception e) {
//            ContextUtil.getInstance().showToastMsg("分享图片到**失败");
                Log.w("hanjiming", "分享失败");
            }
        } else {
            Toast.makeText(mContext, "未检查到QQ，请安装QQ", Toast.LENGTH_LONG).show();
        }
    }

    //权限数组（申请定位）
    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};

    //返回code
    private static final int OPEN_SET_REQUEST_CODE = 100;

    //调用此方法判断是否拥有权限
    private void initPermissions() {

        if (lacksPermission()) {//判断是否拥有权限
            //请求权限，第二参数权限String数据，第三个参数是请求码便于在onRequestPermissionsResult 方法中根据code进行判断
            ActivityCompat.requestPermissions(this, permissions, OPEN_SET_REQUEST_CODE);
        } else {
            //拥有权限执行操作
            if (isSanFang) {
                //第三方
                if (TextUtils.isEmpty(path)){
                    initnQRcodeBitmap();
                } else {
                    sanFangFX();
                }
            } else {
                //系统
                intoTheSoftware();
            }

        }
    }

    //如果返回true表示缺少权限
    public boolean lacksPermission() {
        for (String permission : permissions) {
            //判断是否缺少权限，true=缺少权限
            if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {//响应Code
            case OPEN_SET_REQUEST_CODE:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(mContext, "未拥有相应权限", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                    //拥有权限执行操作
                } else {
                    Toast.makeText(mContext, "未拥有相应权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_jrrj:
                showDialog();
                break;
            case R.id.btn_more_software:

                toMoreSoftWare();

                break;
            case R.id.btn_sure:
                break;
            case R.id.btn_add_friends:
                if (mAllDataEntry != null && mAllDataEntry.aqq != null) {
                    toWZ(mAllDataEntry.aqq.qq);
//                    DialogUtils.showQQDialog(mContext, mAllDataEntry.aqq.qq, "QQ交流群：");
                }
                break;
            case R.id.ll_luolizibo:
                if (mAllDataEntry != null && mAllDataEntry.aqq != null) {
                    toWZ(mAllDataEntry.aLuoliZhibo.url);
                }
                break;
            case R.id.ll_qq_qun:
                //QQ交流群
                if (mAllDataEntry != null && mAllDataEntry.aqq != null) {
                    toWZ(mAllDataEntry.aqq.qq);
//                    DialogUtils.showQQDialog(mContext, mAllDataEntry.aqq.qq, "QQ交流群：");
                }
                break;
        }
    }


    private void toMoreSoftWare() {
        if (mAllDataEntry != null && mAllDataEntry.aGengduoruanjian != null && mAllDataEntry.aBanner != null) {
            toWZ(mAllDataEntry.aGengduoruanjian.url);
        }
    }

    public void getAsyn() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://43.252.231.153/yqr202006/banner/getAll").build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //...
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String result = response.body().string();
                    //处理UI需要切换到UI线程处理
                    ((Activity) mContext).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // 在这里执行你要想的操作 比如直接在这里更新ui或者调用回调在 在回调中更新ui
                            Log.w("hanjiming", result.toString());
                            mAllDataEntry = JsonObjectUtils.getAllDataEnty(result);
                            refreshData();
                        }
                    });
                }
            }
        });
    }

    private void refreshData() {
        if (mAllDataEntry == null) {
            return;
        }
        if (mAllDataEntry.aLuoliZhibo == null) {
            return;
        }
        imagePath.clear();
        imageTitle.clear();
        imagePath.add(UriApi.URI_API + mAllDataEntry.aBanner.path);
        imageTitle.add("测试1");
        refreshBanner();
        tvZBName.setText("" + mAllDataEntry.aLuoliZhibo.name);
        if (TextUtils.isEmpty(mAllDataEntry.aLuoliZhibo.path)) {
            return;
        }
        Glide.with(mContext).load(UriApi.URI_API + mAllDataEntry.aLuoliZhibo.path)
                .apply(new RequestOptions().placeholder(R.mipmap.ic_launcher))
                .into(imageView);
    }


    private void showDialog() {
        DialogUtils.showDialog(mContext, mWidth, new OnclickListeners() {
            @Override
            public void jinriruanjian() {
                if (INDEX >= 3) {
                    DialogUtils.dismissDialog();
                    moreSoftware();
                } else {
                    Toast.makeText(mContext, "本软件需要分享到3个100人群才可以使用", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void fenxiang() {
                initPermissions();
            }
        });
    }


    //分享判断
    public void intoTheSoftware() {
        try {
            if (QRcodeBitmap == null) {
                initnQRcodeBitmap();
            }
            shareImageToQQ(QRcodeBitmap);
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("hanjiming", "失败");
        }
    }

    private void sanFangFX() {
        if(mAllDataEntry == null || mAllDataEntry.aErweima == null || TextUtils.isEmpty(mAllDataEntry.aErweima.url)){
            Toast.makeText(mContext, "请求数据失败，请重试！", Toast.LENGTH_LONG).show();
            return;
        }
        ShareUtils.showShare(mContext, "永久免费午夜电影", mAllDataEntry.aErweima.url, "亚洲、欧美，日韩，制服诱惑中文字幕，剧情精彩",
                "http://pic3.pocoimg.cn/image/poco/works/96/2020/0627/23/15932704726372102_201401996.jpg?imageMogr2/auto-orient/thumbnail/x800/blur/1x0/quality/100&",
                new PlatformActionListener() {
            @Override
            public void onComplete(cn.sharesdk.framework.Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.w("hanjiming", "platform:" + platform + " hashMap: " + hashMap);
                Toast.makeText(mContext, "分享成功，谢谢支持", Toast.LENGTH_LONG).show();
                refreshDialog(1);
            }

            @Override
            public void onError(cn.sharesdk.framework.Platform platform, int i, Throwable throwable) {
                Toast.makeText(mContext, "分享失败，必须分享到100人群以上才可以哦", Toast.LENGTH_LONG).show();
                refreshDialog(2);
            }

            @Override
            public void onCancel(cn.sharesdk.framework.Platform platform, int i) {
                Toast.makeText(mContext, "取消分享，必须分享到100人群以上才可以哦", Toast.LENGTH_LONG).show();
                refreshDialog(3);
            }

        });

    }

    private void refreshDialog(int type) {
        switch (type) {
            case 1:
                INDEX++;
                break;
            case 2:
                break;
            case 3:
                break;
        }
        showDialog();
    }

    /**
     * 直接分享纯文本内容至QQ好友
     *
     * @param mContext
     * @param content
     */
    public static void shareQQ(Context mContext, String content) {
        try {

            if (PlatformUtil.isInstallApp(mContext, PlatformUtil.PACKAGE_MOBILE_QQ)) {
                Intent intent = new Intent("android.intent.action.SEND");
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                intent.putExtra(Intent.EXTRA_TEXT, content);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity"));
                mContext.startActivity(intent);
            } else {
                Toast.makeText(mContext, "您需要安装QQ客户端", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Log.w("hanjiming", "shareQQ 分享失败");
        }
    }
//    之前有同学说在分享QQ和微信的时候，发现只要QQ或微信在打开的情况下，再调用分享只是打开了QQ和微信，却没有调用选择分享联系人的情况，这里，我要感觉一下@[努力搬砖]同学，他找出了原因。
//    解决办法如下：
//            mActivity.startActivity(intent);//如果微信或者QQ已经唤醒或者打开，这样只能唤醒微信，不能分享
//    请使用 mActivity.startActivity(Intent.createChooser(intent, "Share"));


}
